#!/bin/bash
export ETCD_VERSION="3.6.3"
export HOST_IP=$(hostname -I | awk '{print $1}')
export MASTER_IP=$HOST_IP
export K8S_DIR="/opt/kubernetes"

mkdir -p /var/lib/etcd
mkdir -p $K8S_DIR/config
mkdir -p $K8S_DIR/bin


tar -zxvf etcd-v${ETCD_VERSION}-linux-amd64.tar.gz
cp etcd-v${ETCD_VERSION}-linux-amd64/{etcd,etcdctl,etcdutl} $K8S_DIR/bin


# 创建etcd配置文件

cat > $K8S_DIR/config/etcd.config.yml <<EOF
name: etcd-server
data-dir: /var/lib/etcd
listen-client-urls: http://$MASTER_IP:2379,http://127.0.0.1:2379
advertise-client-urls: http://$MASTER_IP:2379
listen-peer-urls: http://$MASTER_IP:2380
initial-advertise-peer-urls: http://$MASTER_IP:2380
initial-cluster: etcd-server=http://$MASTER_IP:2380
initial-cluster-token: etcd-cluster-0
initial-cluster-state: new
EOF

# 创建etcd服务文件
cat > /etc/systemd/system/etcd.service <<EOF
[Unit]
Description=etcd service
Documentation=https://github.com/coreos/etcd
After=network.target

[Service]
Type=notify
ExecStart=$K8S_DIR/bin/etcd --config-file=$K8S_DIR/config/etcd.config.yml
Restart=always
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

systemctl enable etcd&&systemctl start etcd